#include "showimagewidget.h"
#include <ukui-log4qt.h>
#include <KWindowEffects>

ShowImageWidget::ShowImageWidget(QWidget *parent) : QWidget(parent)
  , m_stackImage (new QImage())
  , m_editImage (new QImage())
  , m_normalImage (new QImage())
  , m_showImageLabel (new QLabel())
  , m_cropLabel (new CropLabel())
  , m_showImageAndCropWidget (new QStackedWidget())
  , m_showImageHLayout (new QHBoxLayout())
  , m_toolbarWidget (new ToolBarWidget())
  , m_mainVLayout (new QVBoxLayout())
  , scannerImagePath(g_config_signal->m_scannerImagePath)
{
    setupGui();
    initConnect();
}

void ShowImageWidget::setupGui()
{
    this->setMinimumSize(QSize(ShowImageWidgetWidth, ShowImageWidgetHeight));
    this->setFocusPolicy(Qt::StrongFocus);

    m_cropLabel->setMinimumSize(QSize(defaultImageLableWidth*0.05, defaultImageLableHeight*0.05));

    m_showImageLabel->setMinimumSize(QSize(387*0.05, 536*0.05));
    m_showImageLabel->installEventFilter(this);

    m_showImageAndCropWidget->addWidget(m_cropLabel);
    m_showImageAndCropWidget->addWidget(m_showImageLabel);
    m_showImageAndCropWidget->setCurrentWidget(m_showImageLabel);

    m_showImageHLayout->setSpacing(0);
    m_showImageHLayout->addSpacing(128);
    m_showImageHLayout->addStretch();
    m_showImageHLayout->addWidget(m_showImageAndCropWidget, 0, Qt::AlignCenter);
    m_showImageHLayout->addStretch();
    m_showImageHLayout->addSpacing(128);
    m_showImageHLayout->setContentsMargins(0, 0, 0, 0);

    m_mainVLayout->setSpacing(0);
    m_mainVLayout->addSpacing(24);
    m_mainVLayout->addStretch();
    m_mainVLayout->addLayout(m_showImageHLayout);
    m_mainVLayout->addSpacing(24);
    m_mainVLayout->addStretch();
    m_mainVLayout->addWidget(m_toolbarWidget, 0, Qt::AlignCenter);
    m_mainVLayout->addSpacing(16);
    m_mainVLayout->setContentsMargins(0, 0, 0, 0);

    this->setLayout(m_mainVLayout);
}

void ShowImageWidget::initConnect()
{
    connect(g_user_signal, &GlobalUserSignal::scanThreadFinishedImageLoadSignal, this, &ShowImageWidget::showNormalImageAfterScan);

    connect(g_user_signal, &GlobalUserSignal::showImageAfterClickedThumbnailSignal, this, &ShowImageWidget::showImageAfterClickedThumbnail);

    connect(g_user_signal, &GlobalUserSignal::saveAsButtonClickedSignal, this, &ShowImageWidget::saveImage);

    connect(g_user_signal, &GlobalUserSignal::toolbarCropOperationSignal, this, &ShowImageWidget::cropSlot);
    connect(g_user_signal, &GlobalUserSignal::toolbarRotateOperationSignal, this, &ShowImageWidget::rotateSlot);
    connect(g_user_signal, &GlobalUserSignal::toolbarMirrorOperationSignal, this, &ShowImageWidget::mirrorSlot);
    connect(g_user_signal, &GlobalUserSignal::toolbarWatermarkOperationSignal, this, &ShowImageWidget::watermarkSlot);

    connect(g_user_signal, &GlobalUserSignal::toolbarZoomoutOperationSignal, this, &ShowImageWidget::zoomoutNormalImage);
    connect(g_user_signal, &GlobalUserSignal::toolbarZoominOperationSignal, this, &ShowImageWidget::zoominNormalImage);

    connect(g_user_signal, &GlobalUserSignal::toolbarBeautyOperationStartSignal, this, &ShowImageWidget::beautyStartSlot);
    connect(g_user_signal, &GlobalUserSignal::doBeautyOperationFinishedSignal, this, &ShowImageWidget::beautyStopSlot);

    connect(g_user_signal, &GlobalUserSignal::toolbarRectifyOperationStartSignal, this, &ShowImageWidget::rectifyStartSlot);
    connect(g_user_signal, &GlobalUserSignal::doRectifyOperationFinishedSignal, this, &ShowImageWidget::rectifyStopSlot);

    connect(g_user_signal, &GlobalUserSignal::toolbarOcrOperationStartSignal, this, &ShowImageWidget::ocrStartSlot);
}

constexpr inline int U(const char *str)
{
    return str[0] + (str[1] ? U(str + 1) : 0);
}

int ShowImageWidget::toUnicode(QString str)
{
    char  *ch;
    QByteArray ba = str.toLatin1();
    ch = ba.data();
    return ch[0] + (ch[1] ? toUnicode(ch + 1) : 0);

}

void ShowImageWidget::setPdfSize(QPdfWriter *pdfWriter, QString size)
{
    switch (toUnicode(size)) {
    case U("A0"):
        pdfWriter->setPageSize(QPageSize(QPageSize::A0));
        break;
    case U("A1"):
        pdfWriter->setPageSize(QPageSize(QPageSize::A1));
        break;
    case U("A2"):
        pdfWriter->setPageSize(QPageSize(QPageSize::A2));
        break;
    case U("A3"):
        pdfWriter->setPageSize(QPageSize(QPageSize::A3));
        break;
    case U("A4"):
        pdfWriter->setPageSize(QPageSize(QPageSize::A4));
        break;
    case U("A5"):
        pdfWriter->setPageSize(QPageSize(QPageSize::A5));
        break;
    case U("A6"):
        pdfWriter->setPageSize(QPageSize(QPageSize::A6));
        break;
    case U("A7"):
        pdfWriter->setPageSize(QPageSize(QPageSize::A7));
        break;
    case U("A8"):
        pdfWriter->setPageSize(QPageSize(QPageSize::A8));
        break;
    case U("A9"):
        pdfWriter->setPageSize(QPageSize(QPageSize::A9));
        break;
    default:
        pdfWriter->setPageSize(QPageSize(QPageSize::A4));
        break;
    }

}

void ShowImageWidget::saveToPdf(QImage img, QString pathname)
{
    QFile pdfFile(pathname);
    pdfFile.open(QIODevice::WriteOnly);
    QPdfWriter *pdfWriter = new QPdfWriter(&pdfFile);
    setPdfSize(pdfWriter, g_sane_object->userInfo.size);

    int resolution = g_sane_object->resolutionValue;
    pdfWriter->setResolution(resolution);

    int pageMargin = 0;
    pdfWriter->setPageMargins(QMarginsF(pageMargin, pageMargin, pageMargin, pageMargin));

    QPainter *pdfPainter = new QPainter(pdfWriter);

    int yCurrentP = 0;
    int xCurrentP = 0;

    QPixmap pixmap = QPixmap::fromImage(img);
    pdfPainter->drawPixmap(xCurrentP, yCurrentP, pixmap.width(), pixmap.height(), pixmap);

    delete pdfPainter;
    delete pdfWriter;
    pdfFile.close();
}

QImage *ShowImageWidget::imageSave(QString filename)
{
    KyInfo() << "save image: " << filename;
    if (g_sane_object->ocrFlag == 0) {
        *m_editImage = m_normalImage->copy();
        if (filename.endsWith(".pdf"))
            return m_editImage;
        if (filename.endsWith(".png") || filename.endsWith(".jpg") || filename.endsWith(".bmp"))
            m_editImage->save(filename);
    } else {
        if (!filename.endsWith(".txt"))
            filename += ".txt";
        QFile file(filename);
        file.open(QIODevice::ReadWrite | QIODevice::Text);
        QByteArray str = g_sane_object->ocrOutputText.toUtf8();
        file.write(str);
        file.close();
    }
    return NULL;
}

QString ShowImageWidget::setPixmapScaled(QImage img, QLabel *lab, double scale)
{
    if (img.isNull()) {
        KyWarning() << "image is null.";
        return "";
    }
    double labWidth = this->width() - 2*ShowImageWidgetSpacing - AddWidthForLargeFontSize;
    double labHeight = this->height() - 24 -24 - 36 -16;

    double imgWidth = defaultScanImageSize.width();
    double imgHeight = defaultScanImageSize.height();

    if(rotationFlag){
        swap(imgWidth,imgHeight);
    }

    qDebug() << "label size: " << lab->size()
             << "this size: " << this->size()
             << "this labsize: " << labWidth << labHeight
             << "defaultImage size: " << defaultScanImageSize
             << "scale: " << scale
             << "image size: " << img.size();

    if (! qFuzzyCompare(scale, 1.0)) {
        proportion = scale;
    } else {
        if ((labWidth / imgWidth) <= (labHeight / imgHeight)) {
            proportion = labWidth / imgWidth;
        } else {
            proportion = labHeight / imgHeight;
        }

    }


    proportionForPercentage = proportion;

    QPixmap pixmap = QPixmap::fromImage(img);
    QPixmap fitpixmap = resizePix(pixmap, img.size()*proportion);

    lab->setPixmap(fitpixmap);
    lab->setFixedSize(QSize(fitpixmap.size()));
    lab->setScaledContents(true);
    lab->setAlignment(Qt::AlignCenter | Qt::AlignVCenter | Qt::AlignHCenter);


    KyInfo() << "proportion: " << proportion
             << "proportionForPercentage: " << proportionForPercentage;

//    int proportionInt = static_cast<int>(proportionForPercentage * 100);
    int proportionInt = qRound(proportionForPercentage * 100);

    KyInfo() << "proportionInt: " << proportionInt;
    QString proportionString = QString("%1").arg(proportionInt) + "%";

    KyInfo() << "proportionString: " << proportionString;
    g_sane_object->percentage = proportionString;

    g_user_signal->toolbarPercentageChanged();

    return proportionString;
}

void ShowImageWidget::setPixmapScaledByProportion(double scaledNumber)
{
    int scaledWidth = static_cast<int>(m_showImageLabel->width() * scaledNumber);
    int scaledHeight = static_cast<int>(m_showImageLabel->height() * scaledNumber);

    KyInfo() << "scaledNumber = " << scaledNumber
             << "scaleWidth = " << scaledWidth
             << "scaleHeight = " << scaledHeight;

    *m_editImage = m_normalImage->copy();

    m_editImage->scaled(scaledWidth, scaledHeight, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    *m_normalImage = m_editImage->copy();
    m_showImageLabel->setPixmap(QPixmap::fromImage(*m_normalImage));
    m_showImageLabel->setScaledContents(true);
}

void ShowImageWidget::getCropArea(int &x1, int &y1, int &x2, int &y2)
{
    if (m_cropLabel->getBeginX() <= m_cropLabel->getEndX()) {
        x1 = m_cropLabel->getBeginX();
        x2 = m_cropLabel->getEndX();
    } else {
        x1 = m_cropLabel->getEndX();
        x2 = m_cropLabel->getBeginX();
    }

    if (m_cropLabel->getBeginY() <= m_cropLabel->getEndY()) {
        y1 = m_cropLabel->getBeginY();
        y2 = m_cropLabel->getEndY();
    } else {
        y1 = m_cropLabel->getEndY();
        y2 = m_cropLabel->getBeginY();
    }

}

double ShowImageWidget::getCurrentPercentage()
{
    QString proportionNoPercentage = g_sane_object->percentage.replace("%", "");

    double percentageDouble;

    percentageDouble = proportionNoPercentage.toDouble() / 100;
    KyInfo() << "percentageDouble = " << percentageDouble
             << "proportionNoPercentage = " << proportionNoPercentage;

    KyInfo() << "percentageDouble = " << percentageDouble;


    return percentageDouble;

}

double ShowImageWidget::getRealPercentage(ShowImageWidget::ZoomStatus zoomType)
{
    QString proportionNoPercentage = g_sane_object->percentage.replace("%", "");

    double percentageDouble;

    if (zoomType == ZoomStatus::ZoomOut) {
        percentageDouble = proportionNoPercentage.toDouble() / 100 - 0.05;
    } else {
        percentageDouble = proportionNoPercentage.toDouble() / 100 + 0.05;
    }
    KyInfo() << "percentageDouble = " << percentageDouble
             << "proportionNoPercentage = " << proportionNoPercentage;

    KyInfo() << "percentageDouble = " << percentageDouble;

    if (zoomType == ZoomStatus::ZoomOut) {
        if (percentageDouble < 0.05) {
            percentageDouble = 0.05;
        }
    KyInfo() << "percentageDouble = " << percentageDouble;
    } else if (zoomType == ZoomStatus::ZoomIn) {
        if (percentageDouble > 2) {
            percentageDouble = 2;
        }
    KyInfo() << "percentageDouble = " << percentageDouble;
    }

    return percentageDouble;
}

void ShowImageWidget::updatePercentageByZoom(double scale)
{
    int percentageInt = qRound(scale * 100.0);

    QString percentageString = QString::number(percentageInt) + "%";
    KyInfo() << "percentage: " << percentageString;

    g_sane_object->percentage = percentageString;

    g_user_signal->toolbarPercentageChanged();

}

void ShowImageWidget::resizeEvent(QResizeEvent *event)
{
    // Must override, otherwise, m_showImageLabel will not auto resize
//    m_showImageLabel->setMinimumSize(QSize(387*0.2, 536*0.2));

    setPixmapScaled(*m_normalImage, m_showImageLabel);

    QWidget::resizeEvent(event);
}


void ShowImageWidget::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_Return:
    case Qt::Key_Enter:
    case Qt::Key_Space:

        if (m_showImageAndCropWidget->currentWidget() == m_cropLabel) {
            KyInfo() << "pressed key(Enter): " << event->key();

            int x1, y1, x2, y2;
            getCropArea(x1, y1, x2, y2);

            QImage cropImage = m_normalImage->copy(x1/proportion, y1/proportion, (x2-x1)/proportion, (y2-y1)/proportion);

            *m_editImage = cropImage;
            setPixmapScaled(*m_editImage, m_cropLabel, proportion);

            *m_normalImage = m_editImage->copy();
            setPixmapScaled(*m_normalImage, m_showImageLabel, proportion);

            m_cropLabel->initCropSettings();


            m_showImageAndCropWidget->setCurrentWidget(m_showImageLabel);

            g_sane_object->cropFlag = 0;
        }
        break;

    case Qt::Key_Z:
        if (event->modifiers() == Qt::ControlModifier) {
            KyInfo() << "pressed key(ctrl+z): " << event->key();

            if (! m_imageStack.isEmpty()) {

                if (m_showImageAndCropWidget->currentWidget() == m_cropLabel) {
                    *m_editImage = m_imageStack.pop();
                    setPixmapScaled(*m_editImage, m_cropLabel);

                    *m_normalImage = m_editImage->copy();
                    setPixmapScaled(*m_normalImage, m_showImageLabel);

                    m_showImageAndCropWidget->setCurrentWidget(m_showImageLabel);
                    g_sane_object->cropFlag = 0;
                } else {
                    *m_editImage = m_imageStack.pop();
                    setPixmapScaled(*m_editImage, m_showImageLabel);

                    *m_normalImage = m_editImage->copy();
                    setPixmapScaled(*m_normalImage, m_showImageLabel);
                    m_showImageAndCropWidget->setCurrentWidget(m_showImageLabel);
                    g_sane_object->cropFlag = 0;

                }
            }

        }
        break;
    case Qt::Key_Escape:
//        KyInfo() << "pressed key(Esc): " << event->key();
//        if (! m_imageStack.isEmpty()) {
//            *m_editImage = m_imageStack.pop();
//            setPixmapScaled(*m_editImage, m_showImageLabel);

//            *m_normalImage = m_editImage->copy();
//            setPixmapScaled(*m_normalImage, m_showImageLabel);
//        }

        break;

    default:
        KyInfo() << "pressed key: " << event->key();
        break;
    }
}

bool ShowImageWidget::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == m_showImageLabel) {
        if (event->type()==QEvent::Wheel) {
            QWheelEvent *wheelEvent=static_cast<QWheelEvent *>(event);
            if (g_sane_object->cropFlag == 1) {
                return QObject::eventFilter(obj,event);
            }
            if (wheelEvent->delta()>0) {
                zoominNormalImage();
            } else {
                zoomoutNormalImage();
            }
        }
    }

    return QObject::eventFilter(obj,event);
}

void ShowImageWidget::showNormalImageAfterScan()
{
    m_imageStack.clear();
    proportionForPercentage = 1.0;

    m_showImageAndCropWidget->setCurrentWidget(m_showImageLabel);


    if (g_config_signal->m_kylinScannerImageDebug) {
        g_sane_object->loadFullScanFileName = g_config_signal->m_openFileName;
    }

    QString loadPath = g_sane_object->loadFullScanFileName;



    matImage = KylinImageCodec::loadImageToMat(loadPath).mat;
    QPixmap pixImage = KylinImageCodec::converFormat(matImage);
    *m_normalImage = pixImage.toImage();


    defaultScanImageSize = m_normalImage->size();

    KyInfo() << "loadPath = " << loadPath
             << "defaultScanImage size: " << defaultScanImageSize
             << "loadm_normalImage size: " << m_normalImage->size()
             << "showImageWidget size: " << m_showImageLabel->size();

    QString percentagedouble = setPixmapScaled(*m_normalImage, m_showImageLabel);

    QString savePath = g_sane_object->saveFullScanFileName;
    KyInfo() << "savePath = " << savePath;

    g_sane_object->normalImagePath = loadPath;

    saveImage(savePath);
}

QPixmap ShowImageWidget::resizePix(const QPixmap &pixmap, const QSize &size)
{
    return pixmap.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
}

void ShowImageWidget::showImageAfterClickedThumbnail(QString loadPath)
{
    m_imageStack.clear();
    proportionForPercentage = 1.0;

    KyInfo() << "loadPath = " << loadPath;

    matImage = KylinImageCodec::loadImageToMat(loadPath).mat;
    QPixmap pixImage = KylinImageCodec::converFormat(matImage);
    *m_normalImage = pixImage.toImage();

    defaultScanImageSize = m_normalImage->size();

    rotationFlag = false;
    QString percentagedouble = setPixmapScaled(*m_normalImage, m_showImageLabel);

    g_sane_object->normalImagePath = loadPath;

    if (g_sane_object->ocrFlag != 0) {
        g_user_signal->toolbarOcrOperationStart();
    }
}

void ShowImageWidget::saveImage(QString filename)
{
    KyInfo() << "Save filename: " << filename;
    QImage *img = NULL;
    img = imageSave(filename);

    if (img) {
        saveToPdf(*img, filename);
    }
}

void ShowImageWidget::cropSlot()
{
    KyInfo() << "Crop begin";

    if (g_sane_object->cropFlag == 0) {
        g_sane_object->cropFlag = 1;

        zoomCurrentNormalImage();

        m_cropLabel->initCropSettings();
        m_showImageAndCropWidget->setCurrentWidget(m_cropLabel);

        *m_editImage = m_normalImage->copy();

        *m_stackImage = m_normalImage->copy();
        m_imageStack.push(*m_stackImage);

        setPixmapScaled(*m_editImage, m_cropLabel);


    }

}

void ShowImageWidget::rotateSlot()
{
    KyInfo() << "Rotate begin";
    if (g_sane_object->cropFlag == 1) {
        return;
    }

    *m_stackImage = m_normalImage->copy();
    m_imageStack.push(*m_stackImage);

    QMatrix matrix;
    matrix.rotate(270);
    *m_editImage = m_normalImage->transformed(matrix);

//    setPixmapScaled(*m_editImage, m_showImageLabel);
    rotationFlag = !rotationFlag;
    *m_normalImage = m_editImage->copy();
    setPixmapScaled(*m_normalImage, m_showImageLabel);
}

void ShowImageWidget::mirrorSlot()
{
    if (g_sane_object->cropFlag == 1) {
        return;
    }

    KyInfo() << "Mirror begin";
    *m_stackImage = m_normalImage->copy();
    m_imageStack.push(*m_stackImage);

    *m_editImage = m_normalImage->mirrored(true, false);

    setPixmapScaled(*m_editImage, m_showImageLabel);

    *m_normalImage = m_editImage->copy();
    setPixmapScaled(*m_normalImage, m_showImageLabel);

}

void ShowImageWidget::watermarkSlot()
{
    KyInfo() << "Watermark begin";
    if (g_sane_object->cropFlag == 1) {
        return;
    }

    WatermarkDialog *dialog = new WatermarkDialog();
//    dialog->setWindowModality(Qt::ApplicationModal);

    QWidget *widget = nullptr;
    QWidgetList widgetList = QApplication::allWidgets();
    for (int i=0; i<widgetList.length(); ++i) {
        if (widgetList.at(i)->objectName() == "MainWindow") {
            widget = widgetList.at(i);
        }
    }
    if (widget) {
        QRect rect = widget->geometry();
        int x = rect.x() + rect.width()/2 - dialog->width()/2;
        int y = rect.y() + rect.height()/2 - dialog->height()/2;
        dialog->move(x,y);
    }

    int ret = dialog->exec();
    KyInfo() << "ret = " << ret;

    if (ret == QDialog::Accepted) {
        QString text = dialog->getLineEditText();
        KyInfo() << text;

        *m_stackImage= m_normalImage->copy();
        m_imageStack.push(*m_stackImage);

        *m_editImage = m_normalImage->copy();

        QPixmap pix;
        pix = QPixmap::fromImage(*m_editImage);

        KyInfo() << "pix size: " << pix.size();


        int spacing = 5;
        int fontSize = pix.width()/30;

        QFont font;
        font.setFamily("NotoSansCJKsc-Regular, NotoSansCJKsc;");
        font.setPointSize(fontSize);
        font.setWeight(400);
        font.setLetterSpacing(QFont::AbsoluteSpacing, spacing);

        QColor color;
        color.setRed(0);
        color.setGreen(0);
        color.setBlue(0);
        color.setAlphaF(0.2);

        QPainter painter(&pix);
        painter.setFont(font);
        painter.setPen(color);
        painter.rotate(15);

        int squareEdgeSize = m_editImage->width() * sin(45) + m_editImage->height() * sin( 45);
        int hCount = squareEdgeSize / ((fontSize + spacing) * (text.size() + 1)) + 1;
        int x = squareEdgeSize / hCount + (fontSize + spacing) * 3;
        int y = x / 2;

        KyInfo() << "hcount = " << hCount
                 << "squareEdgeSize = " << squareEdgeSize
                 << "(x,y) = " << x << y;

        for (int i = 0; i < hCount; ++i) {
            for (int j = 0; j < hCount * 2; ++j) {
                painter.drawText(x * i, y * j, text);
//                KyInfo() << "drawtext: " << text;
            }
        }

        *m_editImage = pix.toImage();


        setPixmapScaled(*m_editImage, m_showImageLabel);

        *m_normalImage = m_editImage->copy();
        setPixmapScaled(*m_normalImage, m_showImageLabel);
    }

    delete dialog;
}

void ShowImageWidget::zoomoutNormalImage()
{
    KyInfo() << "cropFlag = " << g_sane_object->cropFlag;
    if (g_sane_object->cropFlag == 1) {
        return;
    }
    /*setPixmapScaled中的scale=1一方面是初始化数值，
     * 表示将图片恢复为默认尺寸，但是在zoom in/out时，
     * scale=1，表示的则是放到到相对尺寸的100%（100% ！= 默认尺寸）
     * 所以缩放时遇到刚好scale == 1的情况，则采取避开的措施（不会影响显示精度），防止歧义
    */
    double scale = getRealPercentage(ZoomOut);
    if (qFuzzyCompare(scale, 1.0)) {
        scale = 0.999;
    }

    setPixmapScaled(*m_normalImage, m_showImageLabel, scale);

    updatePercentageByZoom(scale);
}

void ShowImageWidget::zoominNormalImage()
{
    KyInfo() << "cropFlag = " << g_sane_object->cropFlag;
    if (g_sane_object->cropFlag == 1) {
        return;
    }
    /*setPixmapScaled中的scale=1一方面是初始化数值，
     * 表示将图片恢复为默认尺寸，但是在zoom in/out时，
     * scale=1，表示的则是放到到相对尺寸的100%（100% ！= 默认尺寸）
     * 所以缩放时遇到刚好scale == 1的情况，则采取避开的措施（不会影响显示精度），防止歧义
    */
    double scale = getRealPercentage(ZoomIn);
    if (qFuzzyCompare(scale, 1.0)) {
        scale = 1.001;
    }

    setPixmapScaled(*m_normalImage, m_showImageLabel, scale);

    updatePercentageByZoom(scale);

}

void ShowImageWidget::zoomCurrentNormalImage()
{
    double scale = getCurrentPercentage();

    setPixmapScaled(*m_normalImage, m_showImageLabel, scale);
    setPixmapScaled(*m_normalImage, m_cropLabel, scale);

    updatePercentageByZoom(scale);
}

void ShowImageWidget::beautyStartSlot()
{
    if (g_sane_object->cropFlag == 1) {
        return;
    }

    *m_stackImage = m_normalImage->copy();
    m_imageStack.push(*m_stackImage);

    saveCurrentPicture();
}

void ShowImageWidget::beautyStopSlot()
{
    loadAfterBROPicture();
}

void ShowImageWidget::rectifyStartSlot()
{
    if (g_sane_object->cropFlag == 1) {
        return;
    }

    *m_stackImage = m_normalImage->copy();
    m_imageStack.push(*m_stackImage);

    saveCurrentPicture();
}

void ShowImageWidget::rectifyStopSlot(bool isTrue)
{
    KyInfo() << "rectify: " << isTrue;

    if (isTrue) {
        loadAfterBROPicture();
    }
}

void ShowImageWidget::ocrStartSlot()
{
    if (g_sane_object->cropFlag == 1) {
        return;
    }

    *m_stackImage = m_normalImage->copy();
    m_imageStack.push(*m_stackImage);

    saveCurrentPicture();
}

void ShowImageWidget::ocrStopSlot()
{
    loadAfterBROPicture();
}

void ShowImageWidget::saveCurrentPicture()
{
    m_normalImage->save(ScanningPicture);
}

void ShowImageWidget::loadAfterBROPicture()
{
    m_normalImage->load(ScanningPicture);
    setPixmapScaled(*m_normalImage, m_showImageLabel);
}
